// src/screens/main/HomeScreen.tsx
import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Image,
  RefreshControl,
  Dimensions,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useSelector } from 'react-redux';
import Icon from 'react-native-vector-icons/MaterialIcons';
import LinearGradient from 'react-native-linear-gradient';
import { RootState } from '../../store/store';
import aiService from "../../services/aiService.ts";
import type { StackNavigationProp } from '@react-navigation/stack';
import type { MainStackParamList } from '../../navigation/MainNavigator';

const { width } = Dimensions.get('window');

type NavigationProp = StackNavigationProp<MainStackParamList>;

interface RecentActivity {
  id: string;
  type: 'chat' | 'translate' | 'voice';
  title: string;
  time: string;
  screen: keyof MainStackParamList;
  params?: any;
}

const HomeScreen: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  const { user } = useSelector((state: RootState) => state.auth);
  const { subscription } = useSelector((state: RootState) => state.subscription);
  const [refreshing, setRefreshing] = useState(false);
  const [usageStats, setUsageStats] = useState({
    chatCount: 0,
    translationCount: 0,
    voiceCount: 0,
    remainingQuota: 100,
  });
  const [recentActivities, setRecentActivities] = useState<RecentActivity[]>([]);

  useEffect(() => {
    loadUsageStats();
    loadRecentActivities();
  }, []);

  const loadUsageStats = async () => {
    try {
      const stats = await aiService.getUsageStats();
      setUsageStats({
        chatCount: stats.daily.chatCount,
        translationCount: stats.daily.translationCount,
        voiceCount: stats.daily.voiceCount,
        remainingQuota: calculateRemainingQuota(stats),
      });
    } catch (error) {
      console.error('Load stats error:', error);
      // 设置默认值，避免显示错误
      setUsageStats({
        chatCount: 0,
        translationCount: 0,
        voiceCount: 0,
        remainingQuota: 100,
      });
    }
  };

  const loadRecentActivities = async () => {
    try {
      const activities: RecentActivity[] = [];

      // 获取最近的聊天记录
      try {
        const chatMessages = await aiService.getRecentChatMessages(3);
        console.log(chatMessages)
        chatMessages.forEach((msg) => {
          activities.push({
            id: `chat_${msg.id}`,
            type: 'chat',
            title: msg.content.length > 30 ? `${msg.content.substring(0, 30)}...` : msg.content,
            time: formatTime(msg.timestamp),
            screen: 'ChatDetail',
            params: { conversationId: msg.conversationId },
          });
        });
      } catch (error) {
        console.warn('Failed to load chat history:', error);
      }

      // 获取最近的翻译记录
      try {
        const translateHistory = await aiService.getTranslationHistory(1, 3);
        translateHistory.translations.forEach((translation) => {
          activities.push({
            id: `translate_${translation.id || Date.now()}`,
            type: 'translate',
            title: `${translation.sourceLang}译${translation.targetLang}：${
                translation.sourceText.length > 20
                    ? `${translation.sourceText.substring(0, 20)}...`
                    : translation.sourceText
            }`,
            time: formatTime(translation.createdAt),
            screen: 'TranslateDetail',
            params: { translationId: translation.id },
          });
        });
      } catch (error) {
        console.warn('Failed to load translation history:', error);
      }

      // 获取最近的语音记录
      try {
        const voiceHistory = await aiService.getVoiceHistory(1, 3);
        voiceHistory.records.forEach((record) => {
          activities.push({
            id: `voice_${record.id || Date.now()}`,
            type: 'voice',
            title: `语音识别：${
                record.text.length > 20
                    ? `${record.text.substring(0, 20)}...`
                    : record.text
            }`,
            time: formatTime(record.createdAt),
            screen: 'VoiceDetail',
            params: { recordId: record.id },
          });
        });
      } catch (error) {
        console.warn('Failed to load voice history:', error);
      }

      // 按时间排序并取前3个
      activities.sort((a, b) => {
        // 提取时间用于排序
        const getTimeValue = (timeStr: string) => {
          if (timeStr === '刚刚') return Date.now();
          if (timeStr.includes('分钟前')) {
            const minutes = parseInt(timeStr.replace('分钟前', ''));
            return Date.now() - minutes * 60 * 1000;
          }
          if (timeStr.includes('小时前')) {
            const hours = parseInt(timeStr.replace('小时前', ''));
            return Date.now() - hours * 60 * 60 * 1000;
          }
          if (timeStr.includes('天前')) {
            const days = parseInt(timeStr.replace('天前', ''));
            return Date.now() - days * 24 * 60 * 60 * 1000;
          }
          return new Date(timeStr).getTime();
        };

        return getTimeValue(b.time) - getTimeValue(a.time);
      });

      setRecentActivities(activities.slice(0, 3));
    } catch (error) {
      console.error('Load recent activities error:', error);
      // 设置默认的虚拟数据作为fallback
      setRecentActivities([
        {
          id: 'default_1',
          type: 'chat',
          title: '暂无最近使用记录',
          time: '刚刚',
          screen: 'MainTabs',
        }
      ]);
    }
  };

  const calculateRemainingQuota = (stats: any): number => {
    if (!subscription) return 20; // 免费用户默认配额较少

    const limits = stats.limits;
    const daily = stats.daily;

    const chatUsage = limits.dailyChatLimit > 0 ? (daily.chatCount / limits.dailyChatLimit) * 100 : 0;
    const translateUsage = limits.dailyTranslationLimit > 0 ? (daily.translationCount / limits.dailyTranslationLimit) * 100 : 0;
    const voiceUsage = limits.dailyVoiceLimit > 0 ? (daily.voiceCount / limits.dailyVoiceLimit) * 100 : 0;

    const avgUsage = (chatUsage + translateUsage + voiceUsage) / 3;
    return Math.max(0, Math.floor(100 - avgUsage));
  };

  const formatTime = (timestamp?: string | Date): string => {
    if (!timestamp) return '刚刚';

    const now = new Date();
    const time = new Date(timestamp);
    const diff = now.getTime() - time.getTime();

    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    return `${days}天前`;
  };

  const onRefresh = React.useCallback(async () => {
    setRefreshing(true);
    await Promise.all([loadUsageStats(), loadRecentActivities()]);
    setRefreshing(false);
  }, []);

  const handleViewAllFeatures = () => {
    // 导航到功能列表页面
    navigation.navigate('FeatureList');
  };

  const handleViewAllActivities = () => {
    // 导航到活动历史页面
    navigation.navigate('ActivityHistory');
  };

  const handleActivityPress = (activity: RecentActivity) => {
    if (activity.screen === 'MainTabs') {
      // 如果是默认项，不执行跳转
      return;
    }

    try {
      if (activity.params) {
        navigation.navigate(activity.screen, activity.params);
      } else {
        navigation.navigate(activity.screen as any);
      }
    } catch (error) {
      console.warn('Navigation error:', error);
      // Fallback to main tabs
      switch (activity.type) {
        case 'chat':
          navigation.navigate('MainTabs', { screen: 'Chat' });
          break;
        case 'translate':
          navigation.navigate('MainTabs', { screen: 'Translate' });
          break;
        case 'voice':
          navigation.navigate('MainTabs', { screen: 'Voice' });
          break;
      }
    }
  };

  const features = [
    {
      id: 'chat',
      title: 'AI聊天',
      icon: 'chat',
      color: ['#667eea', '#764ba2'],
      description: '与AI进行智能对话',
      screen: 'Chat' as const,
    },
    {
      id: 'translate',
      title: '智能翻译',
      icon: 'translate',
      color: ['#f093fb', '#f5576c'],
      description: '多语言实时翻译',
      screen: 'Translate' as const,
    },
    {
      id: 'voice',
      title: '语音转文字',
      icon: 'mic',
      color: ['#4facfe', '#00f2fe'],
      description: '语音识别转文字',
      screen: 'Voice' as const,
    },
    {
      id: 'image',
      title: '图像处理',
      icon: 'image',
      color: ['#43e97b', '#38f9d7'],
      description: '智能图像编辑',
      screen: 'Image' as const,
      comingSoon: true,
    },
  ];

  const stats = [
    { label: '今日聊天', value: usageStats.chatCount.toString(), icon: 'chat-bubble' },
    { label: '翻译次数', value: usageStats.translationCount.toString(), icon: 'translate' },
    { label: '语音识别', value: usageStats.voiceCount.toString(), icon: 'record-voice-over' },
    { label: '剩余配额', value: `${usageStats.remainingQuota}%`, icon: 'data-usage' },
  ];

  const getActivityIcon = (type: string): string => {
    switch (type) {
      case 'chat': return 'chat';
      case 'translate': return 'translate';
      case 'voice': return 'mic';
      default: return 'history';
    }
  };

  // @ts-ignore
  // @ts-ignore
  return (
      <ScrollView
          style={styles.container}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                colors={['#667eea']}
            />
          }
      >
        {/* Header */}
        <LinearGradient
            colors={['#667eea', '#764ba2']}
            style={styles.header}
        >
          <View style={styles.headerContent}>
            <View style={styles.headerLeft}>
              <Text style={styles.greeting}>
                {getGreeting()}, {user?.username || '用户'}
              </Text>
              <Text style={styles.date}>
                {new Date().toLocaleDateString('zh-CN', {
                  weekday: 'long',
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric'
                })}
              </Text>
            </View>
            <TouchableOpacity
                onPress={() => navigation.navigate('MainTabs', { screen: 'Profile' })}
                style={styles.avatarContainer}
            >
              {user?.avatarUrl ? (
                  <Image
                      source={{ uri: user.avatarUrl }}
                      style={styles.avatar}
                  />
              ) : (
                  <View style={styles.avatarPlaceholder}>
                    <Icon name="person" size={30} color="#fff" />
                  </View>
              )}
            </TouchableOpacity>
          </View>

          {/* Subscription Banner */}
          <TouchableOpacity
              style={styles.subscriptionBanner}
              onPress={() => navigation.navigate('Subscription')}
              activeOpacity={0.8}
          >
            <View style={styles.subscriptionLeft}>
              <Icon name="star" size={20} color="#ffd700" />
              <Text style={styles.subscriptionText}>
                当前套餐: {getSubscriptionName(subscription?.plan)}
              </Text>
            </View>
            <View style={styles.upgradeButton}>
              <Text style={styles.upgradeText}>
                {subscription?.plan === 'PREMIUM' ? '管理' : '升级'}
              </Text>
              <Icon name="chevron-right" size={20} color="#fff" />
            </View>
          </TouchableOpacity>
        </LinearGradient>

        {/* Quick Stats */}
        <View style={styles.statsContainer}>
          {stats.map((stat, index) => (
              <View key={index} style={styles.statCard}>
                <View style={styles.statIconContainer}>
                  <Icon name={stat.icon} size={24} color="#667eea" />
                </View>
                <Text style={styles.statValue}>{stat.value}</Text>
                <Text style={styles.statLabel}>{stat.label}</Text>
              </View>
          ))}
        </View>

        {/* Features Grid */}
        <View style={styles.featuresContainer}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>功能</Text>
            <TouchableOpacity onPress={handleViewAllFeatures}>
              <Text style={styles.viewAllText}>查看全部</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.featuresGrid}>
            {features.map((feature) => (
                <TouchableOpacity
                    key={feature.id}
                    style={styles.featureCard}
                    // @ts-ignore
                    onPress={() => !feature.comingSoon && navigation.navigate('MainTabs', { screen: feature.screen })}
                    disabled={feature.comingSoon}
                    activeOpacity={0.7}
                >
                  <LinearGradient
                      colors={feature.color}
                      style={styles.featureGradient}
                  >
                    <Icon name={feature.icon} size={32} color="#fff" />
                    {feature.comingSoon && (
                        <View style={styles.comingSoonBadge}>
                          <Text style={styles.comingSoonText}>即将推出</Text>
                        </View>
                    )}
                  </LinearGradient>
                  <Text style={styles.featureTitle}>{feature.title}</Text>
                  <Text style={styles.featureDescription}>{feature.description}</Text>
                </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* Recent Activity */}
        <View style={styles.recentActivity}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>最近使用</Text>
            <TouchableOpacity onPress={handleViewAllActivities}>
              <Text style={styles.viewAllText}>查看全部</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.activityList}>
            {recentActivities.length > 0 ? (
                recentActivities.map((activity) => (
                    <TouchableOpacity
                        key={activity.id}
                        style={styles.activityItem}
                        onPress={() => handleActivityPress(activity)}
                    >
                      <View style={styles.activityIcon}>
                        <Icon name={getActivityIcon(activity.type)} size={20} color="#667eea" />
                      </View>
                      <View style={styles.activityContent}>
                        <Text style={styles.activityTitle}>{activity.title}</Text>
                        <Text style={styles.activityTime}>{activity.time}</Text>
                      </View>
                      <Icon name="chevron-right" size={24} color="#ccc" />
                    </TouchableOpacity>
                ))
            ) : (
                <View style={styles.emptyActivity}>
                  <Icon name="history" size={48} color="#ccc" />
                  <Text style={styles.emptyText}>暂无使用记录</Text>
                  <Text style={styles.emptySubText}>开始使用AI功能吧！</Text>
                </View>
            )}
          </View>
        </View>

        {/* Tips */}
        <View style={styles.tipsContainer}>
          <LinearGradient
              colors={['#ffeaa7', '#fdcb6e']}
              style={styles.tipCard}
          >
            <Icon name="lightbulb" size={24} color="#f39c12" />
            <View style={styles.tipContent}>
              <Text style={styles.tipTitle}>今日小贴士</Text>
              <Text style={styles.tipText}>
                使用GPT-4模型可以获得更准确的回答，但会消耗更多配额
              </Text>
            </View>
          </LinearGradient>
        </View>
      </ScrollView>
  );
};

// 辅助函数
function getGreeting(): string {
  const hour = new Date().getHours();
  if (hour < 6) return '凌晨好';
  if (hour < 12) return '早上好';
  if (hour < 14) return '中午好';
  if (hour < 18) return '下午好';
  return '晚上好';
}

function getSubscriptionName(plan?: string): string {
  switch (plan) {
    case 'PREMIUM':
      return '高级版';
    case 'BASIC':
      return '基础版';
    default:
      return '免费版';
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  header: {
    paddingTop: 50,
    paddingBottom: 30,
    paddingHorizontal: 20,
    borderBottomLeftRadius: 30,
    borderBottomRightRadius: 30,
  },
  headerContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  headerLeft: {
    flex: 1,
  },
  greeting: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#fff',
  },
  date: {
    fontSize: 14,
    color: '#fff',
    opacity: 0.8,
    marginTop: 5,
  },
  avatarContainer: {
    width: 50,
    height: 50,
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
    borderWidth: 3,
    borderColor: '#fff',
  },
  avatarPlaceholder: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 3,
    borderColor: '#fff',
  },
  subscriptionBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    borderRadius: 15,
    padding: 15,
  },
  subscriptionLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  subscriptionText: {
    color: '#fff',
    marginLeft: 10,
    fontSize: 16,
  },
  upgradeButton: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  upgradeText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 16,
  },
  statsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingHorizontal: 20,
    marginTop: -15,
    marginBottom: 20,
  },
  statCard: {
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 15,
    alignItems: 'center',
    width: (width - 60) / 4,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  statIconContainer: {
    marginBottom: 8,
  },
  statValue: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 4,
  },
  statLabel: {
    fontSize: 11,
    color: '#666',
    textAlign: 'center',
  },
  featuresContainer: {
    paddingHorizontal: 20,
    marginBottom: 20,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 15,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
  },
  viewAllText: {
    fontSize: 14,
    color: '#667eea',
  },
  featuresGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  featureCard: {
    width: (width - 50) / 2,
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 15,
    marginBottom: 15,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  featureGradient: {
    width: 60,
    height: 60,
    borderRadius: 30,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 10,
  },
  comingSoonBadge: {
    position: 'absolute',
    top: -5,
    right: -5,
    backgroundColor: '#ff6b6b',
    borderRadius: 10,
    paddingHorizontal: 8,
    paddingVertical: 2,
  },
  comingSoonText: {
    color: '#fff',
    fontSize: 10,
    fontWeight: 'bold',
  },
  featureTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 5,
  },
  featureDescription: {
    fontSize: 12,
    color: '#666',
  },
  recentActivity: {
    paddingHorizontal: 20,
    marginBottom: 20,
  },
  activityList: {
    backgroundColor: '#fff',
    borderRadius: 15,
    overflow: 'hidden',
    minHeight: 120,
  },
  activityItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  activityIcon: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#f0f0ff',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 15,
  },
  activityContent: {
    flex: 1,
  },
  activityTitle: {
    fontSize: 14,
    fontWeight: '600',
    color: '#333',
  },
  activityTime: {
    fontSize: 12,
    color: '#999',
    marginTop: 2,
  },
  emptyActivity: {
    alignItems: 'center',
    justifyContent: 'center',
    padding: 40,
  },
  emptyText: {
    fontSize: 16,
    color: '#666',
    marginTop: 10,
    fontWeight: '500',
  },
  emptySubText: {
    fontSize: 12,
    color: '#999',
    marginTop: 5,
  },
  tipsContainer: {
    paddingHorizontal: 20,
    marginBottom: 30,
  },
  tipCard: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderRadius: 15,
  },
  tipContent: {
    flex: 1,
    marginLeft: 15,
  },
  tipTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#5f3a1a',
    marginBottom: 5,
  },
  tipText: {
    fontSize: 12,
    color: '#7d5a3a',
    lineHeight: 18,
  },
});

export default HomeScreen;